<template>
  <div class="chart-content-wrapper" @mouseenter="mouseenter()" @mouseleave="mouseleave">
    <TopFilter :title="reportName" ref="topFilter">
      <SingleCheck @singleCheck="singleCheck"></SingleCheck>
      <single-list-filter-without-cb :filter="filterN" :type="'years'"
                                     @confirmSingleSelect="chooseYear">
      </single-list-filter-without-cb>
      <double-check-filter :isParentLinkChild="true" @confirmDoubleSelect="planAreaSelect" defaultText="统筹区" :filter="filterN" type="planArea"></double-check-filter>
      <single-list-filter-without-cb :defaultText="'医疗类别'" :filter="filterN" :type="'insuredTypeSe1'" @confirmSingleSelect="chooseMedicalCategory"></single-list-filter-without-cb>
    </TopFilter>
    <div class="chart-container" v-show="isShowChart">
      <div id="myChart4" class="chart-type1"></div>
      <Summarize :showSummarizeText="conclusion"></Summarize>
    </div>
  </div>
</template>

<script>
  import {setChartHeight,seqencingArr,loadingOpt} from '../../../assets/js/utils.js'
  import {getChartItem4} from "../../../api/api";
  import SingleListFilter from '../../last/filter/single-list-filter.vue'
  import DoubleCheckFilter from '../../last/filter/double-check-filter.vue'
  import TopFilter from '../../last/filter/top-filter1.vue'
  import Summarize from '../../last/summarize/summarize.vue'
  import SingleCheck from '../../last/filter/single-check'
  import SingleListFilterWithoutCb from '../../last/filter/single-list-filter-without-checkbox'
  export default {
    name: 'chart4',
    props:['isChange','filter'],
    components:{
      SingleListFilter,
      DoubleCheckFilter,
      TopFilter,
      Summarize,
      SingleListFilterWithoutCb,
      SingleCheck
    },
    data () {
      return {
        filterN: JSON.parse(JSON.stringify(this.filter)),
        conclusion:'',
        areaCode: null,
        countAvgFlag: "1",
        medicalCategory: this.filter.nc.insuredTypeSecond[2].selectId,
        queryYear:this.filter.years[0],
        reportName:'患者人均/次均医药费用增长比较分析TOP6',
        isShowChart:true,
        height:400
      }
    },
    mounted(){
      let areaCode = []
      this.filter.nc.planArea.map((item,index)=>{
        if(index>0&&index<=6){
          areaCode.push(item.selectId)
        }
      })
      this.areaCode = areaCode.join(',');
      setChartHeight();
      // 基于准备好的dom，初始化echarts实例
      this.myChart = this.$echarts.init(document.getElementById('myChart4') ,null, {renderer: 'canvas'})
      this.getData();
      let that = this;
      this.myChart.on('legendselectchanged',function(params){
        let option = this.getOption();
        let select_key = Object.keys(params.selected);
        if (!params.selected[params.name]) {
          select_key.map(res => {
            option.legend[0].selected[res] = true;
          });
        } else {
          select_key.map(res => {
            option.legend[0].selected[res] = true;
          });
          option.legend[0].selected[params.name] = true;
        }
        let legend = []
        that.myChart.dispatchAction({
          type: 'legendselectchanged',
          batch: legend
        });
        that.myChart.setOption(option)
      })
    },
    watch:{
      isChange(){
        setTimeout(()=>{
          setChartHeight();
          setTimeout(()=>{
            this.myChart.resize();
          },10)
        },101)
      }
    },
    methods:{
      mouseenter(){
        this.$refs.topFilter._hideChartTitle()
      },
      mouseleave() {
        this.$refs.topFilter._showChartTitle()
      },
      getData(){
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          this.myChart.clear();
          this.myChart.showLoading(loadingOpt)
          getChartItem4('report/cntExpGrowthCompareAnalysis',this.areaCode, this.countAvgFlag, this.medicalCategory, this.queryYear).then(response=>{
            let json = response.data;
            if(response.code===0){
              this.isShowChart = true;
              this.myChart.hideLoading();
              this.reportName = json.reportName;
              this.conclusion = json.reportConclusion;
              this.drawLine(json)
            }else{
              this.isShowChart = false;
            }
          }).catch(res=>{
            this.isShowChart = false;
          })
        },300)
      },
      avg(arry){
        let sum=0;
        let len=arry.length;
        for(let i=0;i<len;i++){
          sum+=arry[i];
        }
        let d = parseInt((sum/len)*100)/100;
        return d;
      },
      singleCheck(type){
        //选择均次人次
        this.countAvgFlag = type;
        this.getData();
      },
      chooseYear(year){
        //选择年份后执行事件
        this.queryYear = year;
        this.getData();
      },
      planAreaSelect(filter){
        //统筹区选择
        this.areaCode = filter.join(',');
        this.getData();
      },
      chooseMedicalCategory(filter){
        //选择医疗类型
        this.medicalCategory = filter;
        this.getData();
      },
      drawLine(json){
        let avg = this.avg(json.institutionGrowthRateList)
        let hosName = [];
        json.medInstitutionList.map((item,index)=>{
          let length = item.length;
          if(length>7){
            item = item.substring(0,7)+'...'
          }
          hosName.push(item);
        })
        let max = null
        let min = null
        let num = seqencingArr(json.institutionGrowthRateList,json.avgGrowthRate);
        if(json.avgGrowthRate>0&&num){
          max = num
        }else if(json.avgGrowthRate<0&&num){
          min = -num
        }
        // 绘制图表
        this.myChart.setOption({
          // Make gradient line here
          title : {
            subtext: '单位：元',
            left:50,
            top:15,
            x:'left',
            subtextStyle:{
              color:'#fff'
            }
          },
          grid:[//此参数可在一个dom中划分多个图表 可设置不同图表的位置
            {
              width:60,
              // left:'75%',
              right:70,
              bottom:40,
              top:60,
              tooltip: {
                formatter: "{b}</br>{c}%" //给当前坐标系添加弹窗
              }
            },
            {
              left:120,
              bottom:30,
              top:50,
              right:180,
              tooltip: {
                formatter: "{b}</br>{c}万元" //给当前坐标系添加弹窗
              }
            }
          ],
          legend: {
            left:'center',
            top: '95%',
            icon:'rect',
            itemWidth: 30,
            itemHeight: 6,
            itemGap: 20,
            data:[`${this.queryYear}年`,`${this.queryYear-1}年`],
            textStyle:{
              color:'#fff'
            },
            tooltip: {
              show: true,
              formatter:function(params){
                let txt = '';
                /*if(params.name=='增长额(正)'){
                  txt = '增长额（正）</br>即区域内医疗机构医疗总收入增长额=（区</br>域内医疗机构本年度住院收入+本年度门</br>诊收入）-（区域内医疗机构上年年度院收</br>入+上年度门诊收入）'
                }else if(params.name=='增长额(负)'){
                  txt = '增长额（负）</br>即区域内医疗机构医疗总收入增长额=（区</br>域内医疗机构本年度住院收入+本年度门</br>诊收入）-（区域内医疗机构上年年度院收</br>入+上年度门诊收入）'
                }else{
                  txt = '总额'
                }*/
                return `${params.name}医药费总额`;
              }
            }
          },
          tooltip:{
            show:true,
            textStyle :{
              fontSize:12
            },
            /*trigger: 'axis',
            axisPointer : {            // 坐标轴指示器，坐标轴触发有效
              type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }*/
          },
          xAxis: [{
            type:'value',
            /* show:true,*/
            splitLine: {
              show: false
            },
            position:'top',
            max:max,
            min:min,
            splitNumber:2,
            axisLine:{
              show:false
            },
            axisLabel : {
              formatter: '{value}',
              textStyle: {
                color: '#fff'
              }
            },
            axisTick:{
              show:false
            }

          }, {
            type:'value',
            splitLine: {show: false},
            gridIndex: 1,
            axisLine:{
              show:false
            },
            axisLabel : {
              show:false,
              formatter: '{value}',
              textStyle: {
                color: '#fff'
              }
            },
            axisTick:{
              show:false
            }
          }],
          yAxis: [{
            data: hosName,
            splitLine: {
              show: false
            },
            axisLine:{
              show:true,//显示y轴坐标线并设置为虚线
              lineStyle:{
                lineStyle:{
                  type:'solid',
                  color:'#2a4565'
                }
              }
            },
            axisTick:{
              show:false //不显示y轴坐标的刻度
            },
            axisLabel:{
              show:false //不显示y轴坐标数值
            }
          }, {
            data: hosName,
            gridIndex: 1,
            axisLine:{ //y轴的横线是否显示
              show:true,
              lineStyle:{
                color:'#2a4565'
              }
            },
            axisLabel : {
              formatter: '{value}',
              textStyle: {
                color: '#fff'
              }
            },
            axisTick:{ //y轴的刻度短竖线是否显示
              show:false
            }
          }],
          visualMap: [{
            show: true,
            dimension: 0,
            seriesIndex: 0,
            left: 'center',
            top: 'top',
            itemWidth:10,
            itemHeight:10,
            orient:"horizontal",
            textStyle:{
              color:'#fff'
            },
            pieces:[
              {
                max: json.avgGrowthRate,
                color: '#67ffdb',
                symbol:'circle',
                label: '增长率（低于平均值）',
              }, {
                min: json.avgGrowthRate,
                color: '#2b9ff6',
                symbol:'circle',
                label: '增长率（高于平均值）'
              }
            ],
          }],
          series: [{
            type: 'scatter',
            showSymbol: true,
            data: json.institutionGrowthRateList,
            symbolSize: 10,
            label:{
              show:true,
              position:'right',
              formatter:'{c}%',
              color:'#fff'
            },
            tooltip: {
              show:true,
              formatter:function(par){
                let i = par.dataIndex;
                let txt = '';
                json.medInstitutionList.map((item,index)=>{
                  if(index==i){
                    txt = `<span style="color:${par.color}">${item}</span><br><span style="color:#c7c7c7">增长率：${par.value}%</span>`
                  }
                })
                return txt;
              }
            },
            markLine:{
              label:{
                position: 'start',
                formatter: '{c}%',
                color:'#fff'
              },
              symbol:'none',
              data : [
                {
                  xAxis:json.avgGrowthRate,
                  name: '平均增长率',
                  tooltip: {
                    show:true,
                    formatter: function(par){
                      return `<span style="color:${par.color}">平均增长率</span><br><span style="color:#c7c7c7">${par.value}%</span>`
                    }
                  }
                }
              ],
              lineStyle: {
                color:'#ff6a93'
              }
            }
          }, {
            type: 'bar',
            showSymbol: false,
            name: `${this.queryYear}年`,
            barGap: 0,
            itemStyle:{
              color:'#ff6a93'
            },
            data: json.currYearMedTotalFeeList,
            tooltip: {
              show:true,
              formatter:function(par){
                let i = par.dataIndex;
                let txt = '';
                json.medInstitutionList.map((item,index)=>{
                  if(index==i){
                    txt = `<span style="color:${par.color}">${item}</span><br><span style="color:#c7c7c7">${par.seriesName}：${par.value}万元</span>`
                  }
                })
                return txt;
              }
            },
            label:{
              show:true,
              position:'right',
              formatter:'{c}',
              color:'#fff'
            },
            barMaxWidth:20,
            barWidth: '30%',
            xAxisIndex: 1,
            yAxisIndex: 1
          },{
            type: 'bar',
            name:`${this.queryYear-1}年`,//此值与legend图例对应
            itemStyle:{
              color:'#ffd66a'
            },
            tooltip: {
              show:true,
              formatter:function(par){
                let i = par.dataIndex;
                let txt = '';
                json.medInstitutionList.map((item,index)=>{
                  if(index==i){
                    txt = `<span style="color:${par.color}">${item}</span><br><span style="color:#c7c7c7">${par.seriesName}：${par.value}万元</span>`
                  }
                })
                return txt;
              }
            },
            label:{
              show:true,
              position:'right',
              formatter:'{c}',
              color:'#fff'
            },
            showSymbol: false,
            data: json.lastYearMedTotalFeeList,
            barMaxWidth:20,
            barWidth: '30%',
            xAxisIndex: 1,
            yAxisIndex: 1
          }]
        });
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
